package com.ysd.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ysd.lis.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUserManager {

    private static RedisTemplate<String, String> redisTemplate;
    // redis中token过期时间30*24小时与jwt保持一致
    private static final long REDIS_TIME = 30 * 24 * 60 * 60;


    @Autowired
    public RedisUserManager(RedisTemplate<String, String> redisTemplate, Gson gson) {
        this.redisTemplate = redisTemplate;
    }

    public static boolean storeUser(String token, SysUser sysUser) {
        Gson gson = new GsonBuilder().serializeNulls().create();
        String userJson = gson.toJson(sysUser);
        redisTemplate.opsForValue().set(token, userJson, REDIS_TIME, TimeUnit.SECONDS);
        return true;
    }

    public static void storeOrg(String key, String value) {
        redisTemplate.opsForValue().set(key, value, REDIS_TIME, TimeUnit.SECONDS);
    }

    public static void storeKeyValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value, REDIS_TIME, TimeUnit.SECONDS);
    }

    public static void deleteValueByKey(String key) {
        redisTemplate.delete(key);
    }

    public static String getStoreOrg(String key) {
        return redisTemplate.opsForValue().get(key);
    }


    public static SysUser getUser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String userJson = redisTemplate.opsForValue().get(token);
        Gson gson = new GsonBuilder().serializeNulls().create();
        return gson.fromJson(userJson, SysUser.class);
    }

    public static boolean destroyUser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        Boolean result = redisTemplate.delete(token);
        return result != null && result;
    }
}
